import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 入住登记对话框
 */
public class CheckInDialog extends JDialog {
    private JTextField guestIdField;
    private JTextField nameField;
    private JTextField idCardField;
    private JTextField phoneField;
    private JTextField addressField;
    private JComboBox<String> roomComboBox;
    private JSpinner daysSpinner;
    private JLabel totalAmountLabel;
    private boolean confirmed = false;

    public CheckInDialog(JFrame parent) {
        super(parent, "开放登记", true);
        setupUI();
        loadAvailableRooms();
        setLocationRelativeTo(parent);
    }

    private void setupUI() {
        setSize(500, 600);
        setLayout(new BorderLayout());

        // 主面板
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(Color.WHITE);
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.WEST;

        // 标题
        JLabel titleLabel = new JLabel("客人入住登记");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(HotelManagementSystem.getPrimaryColor());
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 20, 0);
        mainPanel.add(titleLabel, gbc);

        // 客人ID
        gbc.gridwidth = 1;
        gbc.insets = new Insets(8, 8, 8, 8);
        JLabel guestIdLabel = new JLabel("客人ID:");
        guestIdLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 1;
        mainPanel.add(guestIdLabel, gbc);

        guestIdField = new JTextField(15);
        guestIdField.setFont(HotelManagementSystem.getButtonFont());
        guestIdField.setText(generateGuestId());
        guestIdField.setEditable(false);
        gbc.gridx = 1;
        gbc.gridy = 1;
        mainPanel.add(guestIdField, gbc);

        // 姓名
        JLabel nameLabel = new JLabel("姓名:");
        nameLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 2;
        mainPanel.add(nameLabel, gbc);

        nameField = new JTextField(15);
        nameField.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 1;
        gbc.gridy = 2;
        mainPanel.add(nameField, gbc);

        // 身份证号
        JLabel idCardLabel = new JLabel("身份证号:");
        idCardLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 3;
        mainPanel.add(idCardLabel, gbc);

        idCardField = new JTextField(15);
        idCardField.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 1;
        gbc.gridy = 3;
        mainPanel.add(idCardField, gbc);

        // 电话
        JLabel phoneLabel = new JLabel("电话:");
        phoneLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 4;
        mainPanel.add(phoneLabel, gbc);

        phoneField = new JTextField(15);
        phoneField.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 1;
        gbc.gridy = 4;
        mainPanel.add(phoneField, gbc);

        // 地址
        JLabel addressLabel = new JLabel("地址:");
        addressLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 5;
        mainPanel.add(addressLabel, gbc);

        addressField = new JTextField(15);
        addressField.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 1;
        gbc.gridy = 5;
        mainPanel.add(addressField, gbc);

        // 房间选择
        JLabel roomLabel = new JLabel("选择房间:");
        roomLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 6;
        mainPanel.add(roomLabel, gbc);

        roomComboBox = new JComboBox<>();
        roomComboBox.setFont(HotelManagementSystem.getButtonFont());
        roomComboBox.addActionListener(e -> updateTotalAmount());
        gbc.gridx = 1;
        gbc.gridy = 6;
        mainPanel.add(roomComboBox, gbc);

        // 入住天数
        JLabel daysLabel = new JLabel("入住天数:");
        daysLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 7;
        mainPanel.add(daysLabel, gbc);

        daysSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 30, 1));
        daysSpinner.setFont(HotelManagementSystem.getButtonFont());
        daysSpinner.addChangeListener(e -> updateTotalAmount());
        gbc.gridx = 1;
        gbc.gridy = 7;
        mainPanel.add(daysSpinner, gbc);

        // 总金额
        JLabel amountLabel = new JLabel("总金额:");
        amountLabel.setFont(HotelManagementSystem.getButtonFont());
        gbc.gridx = 0;
        gbc.gridy = 8;
        mainPanel.add(amountLabel, gbc);

        totalAmountLabel = new JLabel("¥0");
        totalAmountLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        totalAmountLabel.setForeground(HotelManagementSystem.getAccentColor());
        gbc.gridx = 1;
        gbc.gridy = 8;
        mainPanel.add(totalAmountLabel, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.setBackground(Color.WHITE);

        JButton confirmButton = createStyledButton("确认入住", HotelManagementSystem.getSuccessColor());
        confirmButton.addActionListener(new ConfirmActionListener());
        buttonPanel.add(confirmButton);

        JButton cancelButton = createStyledButton("取消", HotelManagementSystem.getAccentColor());
        cancelButton.addActionListener(e -> dispose());
        buttonPanel.add(cancelButton);

        gbc.gridx = 0;
        gbc.gridy = 9;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(20, 0, 0, 0);
        mainPanel.add(buttonPanel, gbc);

        add(mainPanel, BorderLayout.CENTER);
    }

    private void loadAvailableRooms() {
        List<Room> rooms = DataManager.getInstance().getAllRooms();
        roomComboBox.removeAllItems();

        for (Room room : rooms) {
            if ("空闲".equals(room.getStatus())) {
                String roomInfo = room.getRoomNumber() + " - " + room.getRoomType() + " (¥" + room.getPrice() + "/晚)";
                roomComboBox.addItem(roomInfo);
            }
        }

        if (roomComboBox.getItemCount() == 0) {
            JOptionPane.showMessageDialog(this, "当前没有空闲房间！", "提示", JOptionPane.WARNING_MESSAGE);
        } else {
            updateTotalAmount();
        }
    }

    private void updateTotalAmount() {
        if (roomComboBox.getSelectedItem() != null) {
            String selectedRoom = (String) roomComboBox.getSelectedItem();
            String roomNumber = selectedRoom.split(" - ")[0];

            List<Room> rooms = DataManager.getInstance().getAllRooms();
            for (Room room : rooms) {
                if (room.getRoomNumber().equals(roomNumber)) {
                    int days = (Integer) daysSpinner.getValue();
                    double total = room.getPrice() * days;
                    totalAmountLabel.setText("¥" + total);
                    break;
                }
            }
        }
    }

    private String generateGuestId() {
        return "G" + System.currentTimeMillis();
    }

    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(HotelManagementSystem.getButtonFont());
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setBorder(new EmptyBorder(8, 15, 8, 15));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });

        return button;
    }

    public boolean isConfirmed() {
        return confirmed;
    }

    private class ConfirmActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 验证输入
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(CheckInDialog.this, "请输入客人姓名！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (idCardField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(CheckInDialog.this, "请输入身份证号！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (phoneField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(CheckInDialog.this, "请输入电话号码！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (roomComboBox.getSelectedItem() == null) {
                JOptionPane.showMessageDialog(CheckInDialog.this, "请选择房间！", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                // 获取选择的房间信息
                String selectedRoom = (String) roomComboBox.getSelectedItem();
                String roomNumber = selectedRoom.split(" - ")[0];

                // 计算入住和退房日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date checkInDate = new Date();
                Calendar cal = Calendar.getInstance();
                cal.setTime(checkInDate);
                cal.add(Calendar.DAY_OF_MONTH, (Integer) daysSpinner.getValue());
                Date checkOutDate = cal.getTime();

                // 计算总金额
                List<Room> rooms = DataManager.getInstance().getAllRooms();
                double roomPrice = 0;
                for (Room room : rooms) {
                    if (room.getRoomNumber().equals(roomNumber)) {
                        roomPrice = room.getPrice();
                        break;
                    }
                }
                double totalAmount = roomPrice * (Integer) daysSpinner.getValue();

                // 创建客人信息
                Guest guest = new Guest(
                        guestIdField.getText().trim(),
                        nameField.getText().trim(),
                        idCardField.getText().trim(),
                        phoneField.getText().trim(),
                        addressField.getText().trim());

                // 创建入住记录
                CheckIn checkIn = new CheckIn(
                        guest.getGuestId(),
                        guest.getName(),
                        roomNumber,
                        sdf.format(checkInDate),
                        sdf.format(checkOutDate),
                        totalAmount,
                        "已入住");

                // 保存数据
                DataManager.getInstance().addGuest(guest);
                DataManager.getInstance().addCheckIn(checkIn);
                DataManager.getInstance().updateRoomStatus(roomNumber, "已入住");

                confirmed = true;
                JOptionPane.showMessageDialog(CheckInDialog.this, "入住登记成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(CheckInDialog.this, "登记失败：" + ex.getMessage(), "错误",
                        JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        }
    }
}